<?php

/**
 * Well Framework
 * 
 * Class Translator File
 *
 * @category    
 * @package     Well
 * @subpackage  
 * 
 * @author    valerii lazarevych <valeriy.fremar@gmail.com>
 * @copyright fremar ltd.
 * 
 * @license   default
 * @version   5:04:05 PM | Jan 19, 2012
 */

/**
 * Translator Class
 * 
 * Translate any phrase between 2 language from application languages set.
 * Use dictionary & online translate services.
 */
class Translator
{
    /**
     * Dictionary to translate
     * 
     * @var Dictionary Model
     */
    protected   $dictionary         =       null;
    
    /**
     * Array of online translate services url
     * 
     * @var array
     */
    protected   $OnlineServices     =       array(
                                                   'google'    =>  'http://ajax.googleapis.com/ajax/services/language/translate'
                                                 );        
    
    /**
     * Current user language to translate
     * 
     * @var string  | language code
     */
    private     $toLanguage         =       null;
    
    /**
     * Language translate from
     * 
     * @var string  | language code
     */
    private     $fromLanguage       =       null;

    /**
     * Constructor
     */
    private function __construct()
    {               
        $this->dictionary   =   new Dictionary;
    }        
    
    /**
     * Get language translate to
     * 
     * @return string   |   language code
     */
    protected function translateTo()
    {
        if ( !$this->toLanguage )
              $this->toLanguage   =   ApplicationRegistry::get('locale')->getLanguage();
        
        return $this->toLanguage;
    }
    
    /**
     * Get language translate from
     * 
     * @return string   |   language iso code
     */
    protected function translateFrom()
    {
        if ( !$this->fromLanguage )
              $this->fromLanguage =   'en';
        
        return $this->fromLanguage;
    }

    /**
     * Get Online translation
     * 
     * @param string $text
     * @return string
     */
    protected function onlineTranslate($text)
    {
        $url_prefix = 'http://ajax.googleapis.com/ajax/services/language/translate?v=1.0';
        
        $content         =   array( 'q'          => $text,
                                    'langpair'   => $this->translateFrom() .'|'. $this->translateTo()
                             );        
        $transContext    =   stream_context_create( array('http' => array( 'method'  => 'POST',
                                                                           'content' => $content
                                                                   )));        
        $translated_text =   @file_get_contents( $url_prefix, false, $transContext );
        
//        $text      =    urlencode($text);
//        $from_lang =    urlencode('en');
//        $to_lang   =    urlencode('nl');
// 
//        $langpair = $from_lang . '|' . $to_lang;
// 
//        $service_url = $url_prefix . '&q=' . $text . '&langpair=' . $langpair;
// 
//        $translated_text = @file_get_contents($service_url);
//        var_dump($text);
//        var_dump($from_lang);
//        var_dump($to_lang);
//        var_dump($service_url);
//        var_dump($translated_text);
//        exit;
 
        $json = json_decode($translated_text, true);
 
        return $json['responseStatus'] != 200 ? null : $json['responseData']['translatedText'];
    }

    /**
     * Phrase Translate
     * 
     * @param string|array $text 
     * @return string   |  translation of the text
     */
    public static function translate($phrase)
    {
        $translator  =   new self;        
        
        if ( $translator->translateTo() != $translator->translateFrom() ){
                            
            $phrase   =   ($transPhrase =  $translator->dictionary->getTranslation( $phrase, $translator->translateFrom(), $translator->translateTo()) )
                          ? $transPhrase   : $phrase;   //$translator->onlineTranslate($phrase);            
        }                
        return  $phrase;
    }

    /**
     * Translate html page
     * 
     * @todo optemize method algorithm make it more short & readeable
     * 
     * @param string $htmlBody 
     */
    public static function pageTranslate($page)
    {               
        // Prepared html page translation phrases getting, delete head, script tags
        $htmlHead   =   strstr($page, '<body', true);
        $htmlBody   =   strstr( $page, '<body');
        
        while ( ($script = strpos( $htmlBody, '<script'))
                /*|| ($iframe = strpos( $htmlBody, '<iframe'))*/ ) {
                          
              $scriptEnd    =   !empty($script)  ?  strpos( $htmlBody, '</script>')  :  null;
              
              if ( !empty($script)  &&  $scriptEnd)
                  $htmlBody    =   substr_replace ( $htmlBody, '', $script, $scriptEnd - $script + 12);
                            
//              $iframeEnd    =   !empty($iframe)  ?  strpos( $htmlBody, '</iframe>')  :  null;
//              
//              if ( !empty($iframe)  &&  $iframeEnd)
//                  $htmlBody    =   substr_replace ( $htmlBody, '', $iframe, $iframeEnd - $iframe + 120);
        }        
        // Gettin phrases to translate from html prepared body to array
        $j          =   -1;
        $i          =   strlen($htmlBody);
                
        $read       =   0;
        $phrase     =   $tagName    =   ''; 
        $words      =   array();
        
        while (++$j < $i) {
                                    
            if ( (isset($htmlBody{$j}) ? $htmlBody{$j} : '') == '>'){ 
                
                $read       =  1;
                $phrase     =   '';
                $j++;
            }            
            if ( (isset($htmlBody{$j}) ? $htmlBody{$j} : '') == '<' ){                                                
                                
                $read    =   0;
                $phrase  =   trim($phrase);
                
                foreach (array('&nbsp;','&gt;', '&copy;') as $value) {
                    $phrase    =    str_replace($value, '', $phrase);
                }
                
                if ( $phrase ){
                    $words[]    =   $phrase;                                
                }
            }            
            if ( $read ){                                
                $phrase  .=  $htmlBody{$j};
            }                                 
        }        
        
        // Translate phrases & then replace it                
        foreach ($words as $word) {              
            $page   =   str_replace($word, self::translate($word), $page);
        }        
         
        return  $page;
    }    
    
}

?>
